'use strict';

// This is an example of using p2pspider, you can change the code to make it do
// something else.
var fs = require('fs');
var path = require('path');

var bencode = require('bencode');
var P2PSpider = require('./lib');

var p2p = new P2PSpider({
	nodesMaxSize : 400,
	maxConnections : 800,
	timeout : 10000
});

p2p.ignore(function(infohash, rinfo, callback) {
	var torrentFilePathSaveTo = path.join(__dirname, "torrents", infohash
			+ ".torrent");
	fs.exists(torrentFilePathSaveTo, function(exists) {
		callback(exists); // if is not exists, download the metadata.
	});
});

p2p.on('metadata', function(metadata) {
	var name = metadata.infohash;
	try {
		if (metadata.info.name) {
			name = metadata.info.name;
		}
		if (metadata.info['name.utf-8']) {
			name = metadata.info['name.utf-8'];
		}
	} catch (err) {
	}
	try {
//		console.log("name: %s", name);
//		var suffixIndex = name.toString().lastIndexOf('.');
//		if (suffixIndex > 0) {
//			name=name.toString().substring(0, suffixIndex);
//		} 
		var torrentFilePathSaveTo = path.join(__dirname, "torrents", name+ ".torrent");
		fs.writeFile(torrentFilePathSaveTo, bencode.encode({'info' : metadata.info}), function(err) {
			if (err) {
				return console.error(err);
			}
			console.log(name + ".torrent has saved.");
		});
	} catch (err) {
		console.log(err);
	}
});

p2p.listen(6883, '0.0.0.0');
